<template>
<!--  -->
<!-- 此页面为自定义组件：选择新头像 -->
<!--  -->

    <div class="avatar-upload">
        <div class="avatar-show">
            <!-- 如果用户选择了新头像，则显示选中的文件 -->
            <template v-if="localFile">
                <img :src="localFile" />
            </template>
            <template v-else>
                <!-- 如果用户为QQ登陆，则显示QQ头像 -->
                <img :src="`${modelValue.qqAvatar}`"  v-if="modelValue && modelValue.qqAvatar" />
                <!-- 上述都不符合，则根据登陆用户的Id查询头像 -->
                <img :src="`/api/getAvatar/${modelValue.userId}`"  v-else />
            </template>
        </div>

        <!-- :http-request: 当选择了文件后触发的方法 -->
        <div class="select-btn">
            <el-upload
              name="file"
              :show-file-list="false"
              accept=".png,.PNG,.jpg,.JPG,.jpeg,.JPEG,.gif,.GIF,.bmp,.BMP"
              :multiple="false"
              :http-request="uploadImage"
            >
                <el-button type="primary">选择</el-button>
            </el-upload>
        </div>
    </div>
  
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router"
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

const timestamp = ref("");

//父组件中传来的参数   父组件传递过来的参数，子组件通过defineProps接收
const props = defineProps({
    modelValue: {
        type: Object,
        default: null,
    },
});

const localFile = ref(null);    //选择的头像文件 
const emit = defineEmits();     //子组件通过触发父组件的事件，并将参数传递到父组件

// 选择按钮---选择新头像时触发
const uploadImage = async (file) => {
    file = file.file;
    let img = new FileReader();
    img.readAsDataURL(file);
    img.onload = ({ target }) => {
        localFile.value = target.result;    //解析成base64编码，让 -- 第9行 显示
    };
    emit("update:modelValue", file);       //子组件通过触发父组件的事件，并将参数传递到父组件, file（头像）为参数
};

</script>

<style lang="scss">

.avatar-upload {
    display: flex;
    justify-content: center;
    align-items: end;
    
    .avatar-show {
        background: rgb(245, 245, 245);
        width: 150px;
        height: 150px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        position: relative;

        .iconfont {
            font-size: 50px;
            color: #ddd;
        }
        img {
            width: 100%;
            height: 100%;
        }
        .op {
            position: absolute;
            color: #0e8aef;
            top: 80px;
        }
    }

    .select-btn {
        margin-left: 10px;
        vertical-align: bottom;
    }
}

</style>